//
// ========================================================================
// Copyright (c) 1995 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.ee11.test.support;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.eclipse.jetty.ee11.servlet.ServletContextHandler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.toolchain.test.MavenPaths;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceFactory;
import org.eclipse.jetty.xml.XmlConfiguration;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Allows for setting up a Jetty server for testing based on XML configuration files.
 */
public class XmlBasedJettyServer
{
    private final ResourceFactory.LifeCycle _resourceFactory = ResourceFactory.lifecycle();
    private final List<Resource> _xmlConfigurations;
    private final Map<String, String> _properties = new HashMap<>();
    private final Path _baseDir;
    private Server _server;

    public XmlBasedJettyServer(WorkDir workDir) throws IOException
    {
        _xmlConfigurations = new ArrayList<>();
        Properties properties = new Properties();

        Path rootDir = workDir.getEmptyPathDir();
        _baseDir = Files.createDirectory(rootDir.resolve("base"));
        properties.setProperty("jetty.base", _baseDir.toString());

        Path testDocRoot = MavenPaths.findTestResourceDir("docroots");
        properties.setProperty("test.docroot.base", testDocRoot.toString());

        Path webappsDir = Files.createDirectory(_baseDir.resolve("webapps"));
        properties.setProperty("test.webapps", webappsDir.toString());
        properties.setProperty("jetty.deploy.webappsDir", webappsDir.toString());

        Path environmentsDir = Files.createDirectory(_baseDir.resolve("environments"));
        properties.setProperty("jetty.deploy.environmentsDir", environmentsDir.toString());

        Path keystorePath = MavenPaths.findTestResourceFile("keystore.p12");
        properties.setProperty("jetty.sslContext.keyStorePath", keystorePath.toString());
        properties.setProperty("jetty.sslContext.keyStorePassword", "storepwd");

        Path webdefaultFile = MavenPaths.targetDir().resolve("configs/etc/webdefault-ee11.xml");
        assertTrue(Files.isRegularFile(webdefaultFile), "Missing required file: " + webdefaultFile);
        properties.setProperty("jetty.deploy.defaultsDescriptorPath", webdefaultFile.toString());

        Path testConfig = environmentsDir.resolve("ee11-configs.properties");
        try (OutputStream out = Files.newOutputStream(testConfig))
        {
            properties.store(out, "Generated by " + XmlBasedJettyServer.class.getName());
        }

        for (Object key : properties.keySet())
        {
            _properties.put(String.valueOf(key), String.valueOf(properties.get(key)));
        }
    }

    public void addXmlConfiguration(Resource xmlConfig)
    {
        _xmlConfigurations.add(xmlConfig);
    }

    public void addXmlConfiguration(Path xmlConfigFile)
    {
        _xmlConfigurations.add(_resourceFactory.newResource(xmlConfigFile));
    }

    public void addXmlConfiguration(String testConfigName)
    {
        addXmlConfiguration(MavenPaths.findTestResourceFile(testConfigName));
    }

    public void addTargetFileAsXmlConfiguration(String targetFilename)
    {
        Path file = MavenPaths.targetDir().resolve(targetFilename);
        assertTrue(Files.isRegularFile(file), "Target file does not exist: " + file);
        addXmlConfiguration(file);
    }

    public void addWebApp(String warfilename) throws IOException
    {
        Path war = MavenPaths.targetDir().resolve("webapps").resolve(warfilename);
        assertTrue(Files.isRegularFile(war), "Missing war file: " + war);
        Path dest = _baseDir.resolve("webapps").resolve(warfilename);
        Files.copy(war, dest);
    }

    public void setProperty(String key, String value)
    {
        _properties.put(key, value);
    }

    public void load() throws Exception
    {
        // Ensures that expected Environment exists.
        assertNotNull(ServletContextHandler.ENVIRONMENT);

        Map<String, Object> idMap = new HashMap<>();
        // Configure everything
        for (Resource xmlResource : _xmlConfigurations)
        {
            try
            {
                XmlConfiguration configuration = new XmlConfiguration(xmlResource);
                configuration.getIdMap().putAll(idMap);
                configuration.getProperties().putAll(_properties);
                configuration.configure();
                idMap.putAll(configuration.getIdMap());
            }
            catch (Exception e)
            {
                throw new IllegalStateException("Unable to configure XML: " + xmlResource, e);
            }
        }

        _server = (Server)idMap.get("Server");
        assertNotNull(_server, "Server should not be null (failed load?)");
        _server.setStopTimeout(10000);
    }

    public void start() throws Exception
    {
        _server.addManaged(_resourceFactory);
        _server.start();
    }

    public void stop() throws Exception
    {
        LifeCycle.stop(_server);
    }

    public URI getServerURI()
    {
        return _server.getURI().resolve("/");
    }

    public Server getServer()
    {
        return _server;
    }
}
